<?php

namespace App\Console\Commands;


use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

use App\Admin\Models\Financial\FinancialMoneylog;

class AdminMoneyLog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:AdminMoneyLog';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '运维端生成日记账汇总';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        set_time_limit(-1);
        ini_set('memory_limit', -1);
        Log::info('运维端生成日记账汇总开始');
        // type=1现金、2银行、3储蓄卡
        $this->createadmindata(1);
        Log::info('运维端生成日记账汇总结束-1');
        $this->createadmindata(2);
        Log::info('运维端生成日记账汇总结束-2');
        $this->createadmindata(3);
        Log::info('运维端生成日记账汇总结束');
        return 0;
    }

    protected function createadmindata($type)
    {
        //$log_date = $this->getYesterday();
       // $firstDate = $this->getFirstDay();
        $firstDayMonth =$this->firstDayMonth();
        $lastDayMonth =$this->lastDayMonth();
        $current_day = date('d');
        if ($current_day != '01') {
            return;
        }

        $where = [];
        $where['is_del'] = 1;
        $residue_money = $this->getResidueMoney($where, $type, $lastDayMonth);
        $moneydata = $this->getProfit($where, $type, $firstDayMonth, $lastDayMonth);
        $insdata = [];
        $insmoneydata = [
            'type' => $type,
            'inout_type' => 0,
            'log_date' => $lastDayMonth,
            'abstract' => '本月合计',
            'income_money' => $moneydata['income_money']??0,
            'expenditure_money' => $moneydata['expenditure_money']??0,
            'residue_money' => $residue_money,
            'create_at' => time(),
            'update_at' => time(),
            'issys' => 2
        ];

        $insdata[]=$insmoneydata;


        // 计算季度数据
        list($isSatisfy, $firstQuarter, $lastQuarter) = $this->getMonthQuarter();
        $quarter = $this->checkMoneylog($lastQuarter, $type,'本季度合计');
        if ($isSatisfy === true && empty($quarter)) {
            $quarterdata = $this->getProfit($where, $type, $firstQuarter, $lastQuarter);
            $insquarterdata = [
                'type' => $type,
                'inout_type' => 0,
                'log_date' => $lastQuarter,
                'abstract' => '本季度合计',
                'income_money' =>$quarterdata['income_money']??0,
                'expenditure_money' => $quarterdata['expenditure_money']??0,
                'residue_money' => $residue_money,
                'create_at' => time(),
                'update_at' => time(),
                'issys' => 2
            ];
        }

        if(!empty($insquarterdata)){
            $insdata[]=$insquarterdata;
        }

        // 计算年
        list($isYear,$currentYear)=$this->getYearDate();
        if ($isYear===true&& $currentYear) {//年
            $specifiedDate = new \DateTime($currentYear);
            $lastYear =$specifiedDate->modify('-1 day');
            $firstYear =date('Y')-1;
            $firstYear =$firstYear.'01-01';
            $yeardata=$this->getProfit($where, $type, $firstYear, $lastYear);
            $insyeardata = [
                'type' => $type,
                'inout_type' => 0,
                'log_date' => $lastYear,
                'abstract' => '本年合计',
                'income_money' => $yeardata['income_money']?? 0,
                'expenditure_money' => $yeardata['expenditure_money']?? 0,
                'residue_money' => $residue_money,
                'create_at' => time(),
                'update_at' => time(),
                'issys' => 2
            ];

            if(!empty($insyeardata)){
                $insdata[]=$insyeardata;
            }

        }
        if(!empty($insdata)){
            FinancialMoneylog::query()->insert($insdata);
        }
    }


    /**
     *
     * 获取昨天的日期
     * @return string
     */
    public function getYesterday()
    {
        // 创建一个DateTime对象，代表当前时间
        $currentDate = new \DateTime();
        // 使用modify()方法来获取前一天
        $currentDate->modify('-1 day');
        // 格式化日期为字符串，例如：YYYY-MM-DD
        return $currentDate->format('Y-m-d');
    }

    /**
     * 获取本月的第一天
     * @return string
     */
    public function getFirstDay()
    {
        // 创建一个DateTime对象，默认为当前日期和时间
        $date = new \DateTime();

        // 设置日期为这个月的第一天
        $date->modify('first day of this month');

        return $date->format('Y-m-d');
    }

    /**
     * 获取前一天的门店的余额
     * @param $where
     * @param $type
     * @param $log_date
     * @return int|mixed
     */
    public function getResidueMoney($where, $type, $log_date)
    {
        $maxId = FinancialMoneylog::query()
            ->where($where)
            ->where('type', $type)
            ->where('inout_type', '>', 0)
            ->where('log_date', '<=', $log_date)
            ->max('id');

        return FinancialMoneylog::query()
            ->where($where)
            ->where('id', $maxId)
            ->value('residue_money') ?? 0;
    }


    /**
     * 计算利润
     * @param $where
     * @param $type
     * @param $firstDate
     * @param $log_date
     * @return array|int
     */
    public function getProfit($where, $type, $firstDate, $log_date)
    {
        $profit= FinancialMoneylog::query()
            ->where($where)
            ->where('type', $type)
            ->where('log_date', '>=', $firstDate)
            ->where('log_date', '<=', $log_date)
            ->where('inout_type', '>', 0)
            ->selectRaw("sum(income_money) as income_money, sum(expenditure_money) as expenditure_money")
            ->first();
        return empty($profit)?0:$profit->toArray();
    }


    public function getMonthQuarter()
    {

        // 获取当前日期
        $currentDate = new \DateTime();
        // 获取当前月份
        $currentMonth = $currentDate->format('n');
        // 计算上一个季度的最后一个月
        $lastMonthOfPreviousQuarter = (int)(($currentMonth - 1) / 3) * 3;
        // 处理跨年的情况（如果当前季度是第一季度，则上一个季度是去年的第四季度）
        if ($lastMonthOfPreviousQuarter < 1) {
            $lastMonthOfPreviousQuarter = 12; // 上一季度的最后一个月是 12 月
            $previousQuarterYear = $currentDate->format('Y') - 1; // 上一年
        } else {
            $previousQuarterYear = $currentDate->format('Y'); // 当前年份
        }

        // 计算上一个季度的第一个月
        $firstMonthOfPreviousQuarter = $lastMonthOfPreviousQuarter - 2;
        // 获取上一个季度的第一天
        $firstDayOfPreviousQuarter = new \DateTime($previousQuarterYear . '-' . $firstMonthOfPreviousQuarter . '-01');
        // 获取上一个季度的最后一天
        $lastDayOfPreviousQuarter = new \DateTime($previousQuarterYear . '-' . $lastMonthOfPreviousQuarter . '-01');
        $lastDayOfPreviousQuarter->modify('last day of this month');

        // 判断当前日期是否超过上一个季度的最后一天
        if ($currentDate > $lastDayOfPreviousQuarter) {
            //当前日期已经超过上一个季度的最后一天，满足上一个季度的条件
            $isSatisfy = true;
        } else {
            //当前日期还未超过上一个季度的最后一天，不满足上一个季度的条件
            $isSatisfy = false;
        }
        $firstQuarter = $firstDayOfPreviousQuarter->format('Y-m-d');
        $lastQuarter = $lastDayOfPreviousQuarter->format('Y-m-d');

        return [$isSatisfy, $firstQuarter, $lastQuarter];

    }



    /**
     * 检查季度数据是已存在
     * @param $lastQuarter
     * @param $type
     * @param $abstract
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function checkMoneylog($lastQuarter, $type,$abstract)
    {
        return FinancialMoneylog::query()
            ->where('log_date', $lastQuarter)
            ->where('type', $type)
            ->where('abstract', $abstract)
            ->first();

    }

    /**
     * 获取每年的1月1号
     * @return array
     */
    public function getYearDate()
    {
        // 获取当前日期
        $currentDate = new \DateTime();
         // 获取当前日期的月份和日期
        $currentDay = $currentDate->format('d'); // 获取日（01 到 31）
        $currentMonth = $currentDate->format('m'); // 获取月（01 到 12）
        $currentYear=$currentDate->format('Y-m-d');

         // 判断是否是每年的 1 月 1 号
        if ($currentDay === '01' && $currentMonth === '01') {
            $isYear=true;
        } else {
            $isYear=false;
        }

        return [$isYear,$currentYear];
    }


    public function firstDayMonth()
    {

        $currentDate = new \DateTimeImmutable();

        // 上一个月的第一天
        $firstDayOfLastMonth = $currentDate->modify('first day of last month')->setTime(0, 0);
        return $firstDayOfLastMonth->format('Y-m-d');
    }



    public function lastDayMonth()
    {
        $currentDate = new \DateTimeImmutable();
        // 上一个月的第一天
        $lastDayOfLastMonth = $currentDate->modify('last day of last month')->setTime(23, 59, 59);

        return $lastDayOfLastMonth->format('Y-m-d');
    }


}
